#!/bin/bash

# RocketMQ C++ 客户端安装脚本
# 支持使用已下载的动态库或编译安装

set -e

echo "🚀 安装 RocketMQ C++ 客户端..."

# 检查系统类型
if [[ "$OSTYPE" == "darwin"* ]]; then
    echo "📋 检测到 macOS 系统"
    DYLIB_NAME="librocketmq.dylib"
    INSTALL_DIR="/usr/local/lib"
    IS_MACOS=true
else
    echo "📋 检测到 Linux 系统"
    DYLIB_NAME="librocketmq.so"
    INSTALL_DIR="/usr/local/lib"
    IS_MACOS=false
fi

# 检查是否已存在动态库
if [ -f "$INSTALL_DIR/$DYLIB_NAME" ]; then
    echo "ℹ️  发现已安装的动态库: $INSTALL_DIR/$DYLIB_NAME"
    read -p "是否重新安装？(y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "✅ 使用现有安装"
        exit 0
    fi
fi

# 检查项目目录中是否有已下载的动态库
PROJECT_DYLIB="rocketmq-client-cpp/lib/$DYLIB_NAME"
if [ -f "$PROJECT_DYLIB" ]; then
    echo "📦 发现项目中的动态库: $PROJECT_DYLIB"
    
    # 检查动态库架构
    if [ "$IS_MACOS" = true ]; then
        DYLIB_ARCH=$(file "$PROJECT_DYLIB" | grep -o "x86_64\|arm64" || echo "unknown")
        SYSTEM_ARCH=$(uname -m)
        echo "📋 动态库架构: $DYLIB_ARCH, 系统架构: $SYSTEM_ARCH"
        
        if [ "$SYSTEM_ARCH" = "arm64" ] && [ "$DYLIB_ARCH" = "x86_64" ]; then
            echo "⚠️  架构不匹配警告:"
            echo "   - 系统: ARM64 (M1/M2/M3)"
            echo "   - 动态库: x86_64"
            echo "   - 需要使用 Rosetta 2 运行 Python"
            echo ""
            read -p "是否继续安装？(y/N): " -n 1 -r
            echo
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                echo "❌ 安装已取消"
                exit 1
            fi
        fi
    fi
    
    # 安装已下载的动态库
    echo "📦 安装已下载的动态库..."
    if [ "$EUID" -ne 0 ]; then
        echo "⚠️  需要管理员权限来安装到 $INSTALL_DIR"
        echo "请使用 sudo 运行此脚本"
        exit 1
    fi
    
    sudo cp "$PROJECT_DYLIB" "$INSTALL_DIR/"
    sudo chmod 755 "$INSTALL_DIR/$DYLIB_NAME"
    
    # 更新动态库缓存（Linux）
    if [ "$IS_MACOS" = false ]; then
        echo "🔄 更新动态库缓存..."
        sudo ldconfig
    fi
    
    echo "✅ 动态库安装成功！"
    echo "   位置: $INSTALL_DIR/$DYLIB_NAME"
    
    # 测试动态库
    echo "🧪 测试动态库..."
    if [ "$IS_MACOS" = true ] && [ "$SYSTEM_ARCH" = "arm64" ] && [ "$DYLIB_ARCH" = "x86_64" ]; then
        # 使用 Rosetta 2 测试
        arch -x86_64 python3 -c "
import ctypes
try:
    lib = ctypes.CDLL('$INSTALL_DIR/$DYLIB_NAME')
    print('✅ 动态库加载成功！(使用 Rosetta 2)')
except Exception as e:
    print(f'❌ 动态库加载失败: {e}')
"
    else
        python3 -c "
import ctypes
try:
    lib = ctypes.CDLL('$INSTALL_DIR/$DYLIB_NAME')
    print('✅ 动态库加载成功！')
except Exception as e:
    print(f'❌ 动态库加载失败: {e}')
"
    fi
    
    echo "🎉 安装完成！"
    exit 0
fi

# 如果没有找到已下载的动态库，则进行编译安装
echo "📦 未找到已下载的动态库，开始编译安装..."

# 检查是否为 root 用户（Linux 需要）
if [ "$IS_MACOS" = false ] && [ "$EUID" -ne 0 ]; then
    echo "❌ Linux 系统请使用 sudo 运行此脚本"
    exit 1
fi

# macOS 安装依赖
if [ "$IS_MACOS" = true ]; then
    echo "📦 检查 macOS 依赖..."
    if ! command -v brew &> /dev/null; then
        echo "❌ 请先安装 Homebrew: https://brew.sh/"
        exit 1
    fi
    
    # 安装编译依赖
    brew install cmake openssl@3 zlib pkg-config
fi

# Linux 安装依赖
if [ "$IS_MACOS" = false ]; then
    # 更新包管理器
    apt-get update
    
    # 安装依赖
    echo "📦 安装依赖包..."
    apt-get install -y \
        build-essential \
        cmake \
        git \
        libssl-dev \
        zlib1g-dev \
        pkg-config
fi

# 克隆 rocketmq-client-cpp
echo "📥 克隆 rocketmq-client-cpp..."
cd /tmp
if [ -d "rocketmq-client-cpp" ]; then
    rm -rf rocketmq-client-cpp
fi
git clone https://github.com/apache/rocketmq-client-cpp.git
cd rocketmq-client-cpp

# 编译和安装
echo "🔨 编译 rocketmq-client-cpp..."
mkdir build
cd build

if [ "$IS_MACOS" = true ]; then
    # macOS 编译配置
    cmake .. \
        -DCMAKE_BUILD_TYPE=Release \
        -DOPENSSL_ROOT_DIR=/opt/homebrew/opt/openssl@3 \
        -DOPENSSL_INCLUDE_DIR=/opt/homebrew/opt/openssl@3/include \
        -DBUILD_SHARED_LIBS=ON
else
    # Linux 编译配置
    cmake ..
fi

make -j$(nproc)
make install

# 更新动态库缓存（Linux）
if [ "$IS_MACOS" = false ]; then
    echo "🔄 更新动态库缓存..."
    ldconfig
fi

# 清理
echo "🧹 清理临时文件..."
cd /
rm -rf /tmp/rocketmq-client-cpp

# 验证安装
echo "✅ 验证安装..."
if [ -f "$INSTALL_DIR/$DYLIB_NAME" ]; then
    echo "✅ rocketmq-client-cpp 安装成功！"
    echo "   动态库位置: $INSTALL_DIR/$DYLIB_NAME"
else
    echo "❌ 安装失败，未找到动态库文件"
    exit 1
fi

echo "🎉 安装完成！" 